<?php
namespace My\Model;

use Utuo\UtuoModel;

class ModelArticleModel extends UtuoModel {
	
	protected $adminField = 'customer';
	
	protected $_validate = array(
			array('category','require','栏目类别必须',self::MUST_VALIDATE),
	);
	
	protected $_auto = array(
			array('post_time', 'time', self::MODEL_INSERT, 'function'),
			array('update_time', 'time', self::MODEL_BOTH, 'function'),
	);
	
	protected function _before_insert(&$data, $options) {
		$data['tags'] = $this->getTagIds($data);
		return parent::_before_insert($data, $options);
	}
	
	protected function _before_update(&$data, &$options) {
		$data['tags'] = $this->getTagIds($data);
		return parent::_before_update($data, $options);
	}
	
	/* 获得标签ID字符串 */
	private function getTagIds($data) {
		$tags = $data['tags'];
		$customer = $data['customer'];
		$t = M ( "Tags" );
		$tagIds = array ();
		if ($tags) {
			$tags = explode ( ",", $tags );
			foreach ( $tags as $v ) {
				$v = strip_tags ( trim ( $v ) );
				if (strlen ( $v )) {
					$tag = $t->where ( array (
							"cid" => $customer,
							"name" => $v
					) )->find ();
					if ($tag) {
						$tagIds [] = $tag ['id'];
					} else {
						$tagIds [] = $t->add ( array (
								'cid' => $customer,
								'name' => $v
						) );
					}
				}
			}
		}
		return join ( ",", $tagIds );
	}
	
}